package com.juzipi.demo.jdbc;

import com.juzipi.demo.pojo.Emp;
import com.juzipi.demo.utils.JDBCUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class JdbcTestUtilsDemo {

    public static void main(String[] args) {
        //测试工具类
        List<Emp> empList = new JdbcTestUtilsDemo().findAll();
        StringBuilder stringBuilder = new StringBuilder();
        for (Emp emp: empList) {
            stringBuilder.append(emp);
            System.out.println(emp.getId() +","+ emp.getEname()+","+emp.getJob_id()+","+emp.getMgr()+","+emp.getJoindate()+","+emp.getSalary()+","+emp.getBonus()+","+emp.getDept_id());
        }


    }


    public List<Emp> findAll(){

        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        ArrayList<Emp> list = null;
        try {
            //注册驱动
//            Class.forName("com.mysql.cj.jdbc.Driver");
//            //获取连接
//            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT", "zhangwu", "xjlsj");
            connection = JDBCUtils.getConnection();
            //定义sql语句
            String sql = "select * from emp";
            //获取执行sql的对象
            statement = connection.createStatement();
            //执行sql语句
            resultSet = statement.executeQuery(sql);
            //遍历结果集，封装对象，装载集合
            Emp emp = null;
            list = new ArrayList<>();
            while (resultSet.next()){
                //获取数据
                int id = resultSet.getInt(1);
                String ename = resultSet.getString("ename");
                int job_id = resultSet.getInt("job_id");
                int mgr = resultSet.getInt("mgr");
                Date joindate = resultSet.getDate("joindate");
                double salary = resultSet.getDouble("salary");
                double bonus = resultSet.getDouble("bonus");
                int dept_id = resultSet.getInt("dept_id");
                //创建emp对象,并赋值
                emp = new Emp();
                emp.setId(id);
                emp.setEname(ename);
                emp.setJob_id(job_id);
                emp.setMgr(mgr);
                emp.setJoindate(joindate);
                emp.setSalary(salary);
                emp.setBonus(bonus);
                emp.setDept_id(dept_id);
                //装载集合
                list.add(emp);

            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
//            tryCatch(connection, statement, resultSet);
            JDBCUtils.close(resultSet,statement,connection);
        }

        return list;
    }

}
